<cfscript>
component extends="SimpleDBObject" {

	function init(sdb, domain) {
		variables.sdb = sdb;
		variables.domain = domain;
		super.init();
		return this;
	}

	boolean function exists() {
		try {
			metadata();
		} catch(any e) {
			if (e.errorCode eq "NoSuchDomain") return false;
			else throw(object:e);
		}
		return true;
	}

	function itemCount() {
		return metadata().getItemCount();
	}
	
	function create() {
		local.request = _jobj("com.amazonaws.services.simpledb.model.CreateDomainRequest").init(variables.domain);
		variables.sdb.do("createDomain", local.request);
	}
	
	function delete(boolean force=false) {
		if (!force and itemCount()) throw(type="Application", message="To delete a domain which contains data, use delete(true)");
		local.request = _jobj("com.amazonaws.services.simpledb.model.DeleteDomainRequest").init(variables.domain);
		variables.sdb.do("deleteDomain", local.request);
	}

	function metadata() {
		local.request = _jobj("com.amazonaws.services.simpledb.model.DomainMetadataRequest").init(variables.domain);
		return variables.sdb.doSync("domainMetadata", local.request);	
	}

	function serializeToFile(path, boolean overwrite=false) {
		var qry = select().limit(2500);
		var file = FileOpen(path, overwrite?"write":"append");
		FileWrite(file, "[");
		while (qry.hasmore()) {
			var result = qry.execute();
			loop from="1" to="#ArrayLen(result)#" index="local.i" {
				if (local.i gt 1) FileWrite(file, ",");
				FileWriteLine(file, SerializeJson(result[local.i].toMemento().data));
			}
		}
		FileWrite(file, "]");
		FileClose(file);
	}

	/* Factories */
	
	function item(itemName) {
		return new CachedItem(variables.sdb, variables.domain, itemName);
	}
	
	function select() {
		return new Select(variables.sdb).domain(variables.domain);
	}
	
}
</cfscript>